import { useEffect, useState } from 'react';
import { useCall } from '.';

function useToggle(controlled, handler) {
  const [value, setValue] = useState(controlled ?? false);
  const toggle = useCall(() => setValue(!value));

  useEffect(() => {
    if (typeof controlled === 'boolean' && value !== controlled) toggle();
  }, [controlled]);

  useEffect(() => {
    if (typeof handler === 'function') handler(value);
  }, [value]);

  return [value, toggle];
}

export default useToggle;
